package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Admin;
import com.example.mapper.AdminMapper;
import com.example.service.AdminService;
import com.example.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Admin login(String username, String password) {
        log.info("管理员登录: username={}", username);
        
        try {
            // 1. 根据用户名查询管理员
            LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Admin::getUsername, username)
                       .eq(Admin::getDeleted, 0);
            
            log.debug("查询条件: {}", queryWrapper.getCustomSqlSegment());
            Admin admin = this.getOne(queryWrapper);
            log.debug("查询结果: {}", admin);
            
            if (admin == null) {
                log.warn("管理员不存在: username={}", username);
                throw new RuntimeException("管理员不存在");
            }
            
            // 2. 校验密码
            String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            if (!admin.getPassword().equals(encryptedPassword)) {
                log.warn("密码错误: username={}", username);
                throw new RuntimeException("密码错误");
            }
            
            // 3. 校验管理员状态
            if (admin.getStatus() != 1) {
                log.warn("管理员已被禁用: id={}", admin.getId());
                throw new RuntimeException("管理员已被禁用");
            }
            
            // 4. 生成token
            String token = UUID.randomUUID().toString().replace("-", "");
            LocalDateTime expireTime = LocalDateTime.now().plusHours(12); // 12小时有效期
            
            // 5. 更新token信息
            admin.setToken(token);
            admin.setTokenExpireTime(expireTime);
            boolean success = this.updateById(admin);
            
            if (!success) {
                log.error("更新token失败: id={}", admin.getId());
                throw new RuntimeException("登录失败，请稍后重试");
            }
            
            log.info("管理员登录成功: id={}, username={}", admin.getId(), username);
            return admin;
        } catch (Exception e) {
            log.error("登录异常", e);
            throw new RuntimeException("登录失败，请稍后重试");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAdmin(Admin admin) {
        // 1. 加密密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        admin.setPassword(encryptedPassword);
        
        // 2. 设置默认状态
        if (admin.getStatus() == null) {
            admin.setStatus(1);
        }
        
        return save(admin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAdmin(Admin admin) {
        // 1. 如果修改了密码，需要加密
        if (admin.getPassword() != null) {
            String encryptedPassword = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
            admin.setPassword(encryptedPassword);
        }
        
        return updateById(admin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        Admin admin = getById(id);
        if (admin == null) {
            return false;
        }
        admin.setStatus(status);
        return updateById(admin);
    }
} 